import { computed, ref } from 'vue';

import { defineStore } from 'pinia';

// import { getDictDataList } from '@/api/system/dict';
import { Apis } from '#/api';
import dataModule from '#/utils/dict/static.data';

const DICT_STORAGE_KEY = 'DICT_KEY';

export interface DictDataVO {
  dictType: string;
  label: string;
  value: null | number | string;
  isDefault: boolean;
  colorType: string;
  cssClass: string;
}

export const useDictStore = defineStore('app-dict', () => {
  /** 是否初始化字典，是的话每次应用自动加载，后续走缓存，否的话每次请求 */
  const initDict = ref(true);
  /** 字典合集，仅initDict为true时生效 */
  const dictMap = ref<Record<string, DictDataVO[]>>({});
  /** 是否已设置字典合集，仅initDict为true时生效 */
  const isSetDict = ref(false);
  /** 每次新查询字典时的查询缓存，单位：秒 主要用于循环获取数据显示label的场景，建议不低于10s */
  const expireAfterSeconds = ref(30);

  /** 获取所有字典数据 */
  const getDictMap = computed(() => dictMap.value);
  /** 判断是否已设置字典表 */
  const getIsSetDict = computed(() => isSetDict.value);

  /**
   * 设置字典信息
   *
   * @returns
   */
  const setDictMap = async (): Promise<boolean> => {
    try {
      // 模拟网络请求
      // await new Promise((resolve) => setTimeout(resolve, 2000));

      const data = await Apis.dictData.get_page({
        params: { pageNum: 1, pageSize: 10_000 },
      });
      const dictDataMap: Record<string, DictDataVO[]> = {};
      // 处理静态字典数据
      Object.keys(dataModule).forEach((dictType) => {
        const dictEntries = dataModule[dictType];
        dictEntries.data.forEach((dictData) => {
          dictData.type = dictType;

          if (!dictDataMap[dictType]) {
            dictDataMap[dictType] = [];
          }
          dictDataMap[dictType].push({
            value: dictData.value,
            label: dictData.name,
            colorType: dictData.colorType,
            cssClass: dictData.cssClass,
            ...dictData,
          } as DictDataVO);
        });
      });

      // 处理动态字典数据
      data?.rows.forEach((dictData: any) => {
        if (!dictDataMap[dictData.type]) dictDataMap[dictData.type] = [];
        dictDataMap[dictData.type].push({
          value: dictData.value,
          label: dictData.name,
          colorType: dictData.colorType,
          cssClass: dictData.cssClass,
          ...dictData,
        } as DictDataVO);
      });

      console.log('[ dictDataMap ] >', dictDataMap);
      dictMap.value = dictDataMap;
      isSetDict.value = true;
      return true;
    } catch (error) {
      console.error('字典数据获取失败：', error);
      return false;
    }
  };

  /** 获取字典数据 输入字典数组，输出包含对应类型的字典对象 */
  const getDictData = async (
    dictTypeArr: string[],
  ): Promise<Record<string, DictDataVO[]>> => {
    const newDictMap: Record<string, DictDataVO[]> = {};

    return await new Promise((resolve) => {
      if (
        initDict.value &&
        isSetDict.value &&
        Object.keys(dictMap.value).length > 0
      ) {
        dictTypeArr.forEach((dictType) => {
          newDictMap[dictType] = dictMap.value[dictType] || [];
        });
        resolve(newDictMap);
      }

      // if (!isSetDict.value) {
      //   console.warn('字典数据尚未加载，正在等待...');

      //   const checkInterval = setInterval(() => {
      //     console.warn('字典数据加载中...');

      //     if (isSetDict.value) {
      //       console.warn('字典数据完成.');
      //       clearInterval(checkInterval);
      //       dictTypeArr.forEach((dictType) => {
      //         newDictMap[dictType] = dictMap.value[dictType] || [];
      //       });
      //       resolve(newDictMap);
      //     }
      //   }, 45);
      // }

      // try {
      //   return {};
      // } catch (error) {
      //   console.error('getDictMap 函数报错：', error);
      //   return {};
      // }
      resolve(newDictMap);
    });
  };

  /**
   * 获取指定类型的具体的某个字典数据信息，数据默认会存在30秒缓存，以备快速使用
   *
   * @returns Array
   */
  const getDictInfo = async (dictType: string): Promise<DictDataVO[]> => {
    const StorageKey = `${DICT_STORAGE_KEY}:${dictType}`;
    try {
      localStorage.setItem(StorageKey, JSON.stringify(dictMap.value));
      const dictDataMap = (await getDictData([dictType])) || {};
      setTimeout(() => {
        localStorage.removeItem(StorageKey);
      }, expireAfterSeconds.value * 1000);
      return JSON.parse(JSON.stringify(dictDataMap[dictType])) || [];
    } catch (error) {
      console.error('getDictInfo函数报错：', error);
      return [];
    }
  };

  /**
   * 获取指定类型的具体的某个字典数据名称，数据默认会存在30秒缓存，以备快速使用
   *
   * @returns DictDataVO
   */
  const getDictDataInfo = async (
    dictType: string,
    value: string,
  ): Promise<DictDataVO> => {
    const dictDataMap = (await getDictInfo(dictType)) || [];
    return (
      dictDataMap.find((item) => item.value === value) || ({} as DictDataVO)
    );
  };

  /**
   * 获取指定类型的具体的某个字典数据名称，数据默认会存在30秒缓存，以备快速使用
   *
   * @returns DictDataVO
   */
  const getDictDataLabel = async (
    dictType: string,
    value: string,
  ): Promise<string> => {
    const dictDataMap = (await getDictInfo(dictType)) || [];
    const info =
      dictDataMap.find((item) => item.value === value) || ({} as DictDataVO);
    return info.label;
  };

  function $reset() {
    // loginLoading.value = false;
  }

  return {
    initDict,
    dictMap,
    isSetDict,
    expireAfterSeconds,
    getDictMap,
    getIsSetDict,
    setDictMap,
    getDictData,
    getDictInfo,
    getDictDataInfo,
    getDictDataLabel,
    $reset,
  };
});
